<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>角色管理</title>
  <link rel="stylesheet" href="/layui/layuiadmin/layui/css/layui.css" media="all">
  <link rel="stylesheet" href="/layui/layuiadmin/style/admin.css" media="all">
  <link rel="stylesheet" href="/js/css/clearcss.css" media="all">
  <style>
    #addRoleModel{
      padding:20px;
      display: none;
    }
    #menuList{
      border: 1px solid #e3e3e3;
      min-height: 360px;
    }
  </style>
</head>
<body>
<div class="layui-fluid">
  <div class="layui-row layui-col-space15">
    <div class="layui-col-md12">
      <div class="layui-card">
        <div class="layui-card-body">
          <table id="roleList" lay-filter="roleList" lay-data="{id:'roleList'}"></table>
        </div>
        <div type="text/html" id="role_list" style="display:none">
          <th:block th:if="${delete==1}">
            <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">删除</a>
          </th:block>
          <th:block th:if="${add==1}">
            <a class="layui-btn layui-btn-normal layui-btn-sm" lay-event="addRole">添加</a>
          </th:block>
        </div>
        <script type="text/html" id="test-table-operate-barDemo">
          <th:block th:if="${edit==1}">
            <a class="layui-btn layui-btn-xs" lay-event="edit">编辑/详情</a>
          </th:block>
          <th:block th:if="${edit==0}">
            <a class="layui-btn layui-btn-xs" lay-event="check">查看</a>
          </th:block>
        </script>
      </div>
    </div>
  </div>
</div>
<!--添加角色权限Model-->
<div id="addRoleModel">
  <form class="layui-form layui-form-pane" action="" lay-filter="formTest1">
    <div class="layui-form-item">
      <label class="layui-form-label">角色名称</label>
      <div class="layui-input-block">
        <input type="text" name="roleName" id="roleName" lay-verify="required" placeholder="请输入角色名称" autocomplete="off" class="layui-input">
      </div>
    </div>
  </form>
  <form class="layui-form layui-form-pane" action="" lay-filter="formTest1">
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">权限设置</label>
      <div class="layui-input-block">
        <div id="menuList"></div>
      </div>
    </div>
  </form>
</div>
<script src="/layui/layuiadmin/layui/layui.js"></script>
<!--<script type="text/javascript" src="/js/jquery-1.8.0.js"></script>-->
<script type="text/javascript" src="/js/jquery-3.7.1.min.js"></script>
<script>
  MenuData=null
  layui.use(['table','layer','tree','form'], function(){
    let table = layui.table;
    let layer=layui.layer;
    let tree=layui.tree;
    let form=layui.form;
    $.post('/user/getMenuList',function(data){
      MenuData=data
      tree.render({
        elem: '#menuList'  //绑定元素
        ,showCheckbox:true
        ,checkChild: false
        ,data: data
        ,id: 'demoId' //定义索引
      });
    },'json');
    table.render({
      elem: '#roleList'
      ,url: '/user/role' //数据接口
      ,page: true //开启分页
      ,limit:15
      ,limits:[15,20,30,50,100]
      ,toolbar:'#role_list'
      ,defaultToolbar: ['filter', 'print']
      ,loading:true
      ,height: 'full-50'
      ,cols: [
        [ //表头
          {type:'checkbox', fixed: 'left'}
          ,{field: 'id', title: 'ID',  hide:'hide'}
          ,{field: 'title', title: '角色名称',  sort: true,}
          ,{field: 'content', title: '值',  hide:'hide'}
          ,{field: 'peoples', title: '当前人数',  sort: true,}
          ,{align:'center', fixed: 'right', toolbar: '#test-table-operate-barDemo'}
        ]
      ]
    });
    table.on('toolbar(roleList)', function(obj){
      var checkStatus = table.checkStatus(obj.config.id);
      switch(obj.event){
        case 'addRole':
          layer.open({
            type: 1,
            title:'添加角色',
            area: ['550px', '600px'], //自定义文本域宽高
            content: $('#addRoleModel'), //这里content是一个普通的String
            btn: ['提交', '取消'],//这里content是一个普通的String
            btnAlign: 'c',
            cancel: function(index, layero){
              fromClear();
              tree.reload('demoId', {
                //新的参数
              });
            },
            success: function(layero, index){
              // 添加form标识
              layero.addClass('layui-form');
              // 将保存按钮改变成提交按钮
              layero.find('.layui-layer-btn0').attr({
                'lay-filter': 'testttt',
                'lay-submit': ''
              });
              form.render();
            },
            yes:function(index,layero){
              form.on('submit(testttt)',function(data){
                let roleName=$("#roleName").val()//角色名称
                let checkedData = tree.getChecked('demoId'); //获取选中节点的数据
                let a=JSON.stringify(checkedData).match( /(?<=("id":)).*?(?=,)/g).toString();
                $.post('/user/addRole', {roleName:roleName,roleCont:a},function(data){
                  if(data.code=="suss"){
                    layer.closeAll();
                    layer.msg("添加成功")
                    table.reload('roleList', {
                      url: '/user/role'
                    });
                    fromClear()
                    tree.reload('demoId', {
                      //新的参数
                    });
                  }else{
                    layer.msg("添加失败，请联系管理员", {
                      icon: 2,
                      time: 2000 //2秒关闭（如果不配置，默认是3秒）
                    });
                  }
                },'json');
              })
            },
            btn2:function(index,layero){
              fromClear();
              tree.reload('demoId', {
                //新的参数
              });
            }
          });
          break;
        case "del":
          let lh=checkStatus.data.length
          let ids=[];
          for (let i=0;i<lh;i++){
            ids.push(checkStatus.data[i].id)
          }
          if(ids.length==0){
            layer.msg("请选择要删除的角色")
          }else{
            layer.confirm('是否删除选中的角色？<br/>删除后该角色用户权限将清空，请确认', function(index){
              $.post('/user/DelRole',{ids:ids.toString()},function(data){
                if(data.code=="suss"){
                  layer.close(index);
                  layer.msg("删除成功")
                  table.reload('roleList', {
                    url: '/user/role'
                  });
                }else{
                  layer.msg("删除失败，请联系管理员", {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                  });
                }
              },'json');
              layer.close(index);
              //向服务端发送删除指令
            });
          }
          break;
      };
    });
    table.on('tool(roleList)', function(obj){
      var data2 = obj.data; //获得当前行数据
      var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
      let Tid=data2.id;
      if(layEvent === 'edit'){
        form.val("formTest1", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
          "roleName": data2.title // "name": "value"
        });
        if(data2.content!=undefined){
          let a=data2.content.split(",");
          console.log(a)
          tree.setChecked('demoId', a);
        }else{
          tree.reload('demoId', {
            //新的参数
          });
        }
        layer.open({
          type: 1,
          title:'修改角色',
          area: ['550px', '600px'], //自定义文本域宽高
          content: $('#addRoleModel'), //这里content是一个普通的String
          btn: ['提交', '取消'],//这里content是一个普通的String
          btnAlign: 'c',
          cancel: function(index, layero){
            fromClear();
            tree.reload('demoId', {
              //新的参数
            });
          },
          success: function(layero, index){
            // 添加form标识
            layero.addClass('layui-form');
            // 将保存按钮改变成提交按钮
            layero.find('.layui-layer-btn0').attr({
              'lay-filter': 'testttt',
              'lay-submit': ''
            });
            form.render();
          },
          yes:function(index,layero){
            form.on('submit(testttt)',function(data){
              let roleName=$("#roleName").val()//角色名称
              let checkedData = tree.getChecked('demoId'); //获取选中节点的数据
              if(checkedData.length==0){
                layer.msg("请设置权限")
                return
              }
              let a=JSON.stringify(checkedData).match( /(?<=("id":)).*?(?=,)/g).toString();
              li= layer.load(2);
              $.post('/user/editRole', {roleName:roleName,roleCont:a,id:Tid},function(data){
                if(data.code=="suss"){
                  layer.closeAll();
                  layer.msg("修改成功")
                  table.reload('roleList', {
                    url: '/user/role'
                  });
                  fromClear()
                  tree.reload('demoId', {
                    //新的参数
                  });
                }else{
                  layer.close(li);
                  layer.msg("修改失败，请联系管理员", {
                    icon: 2,
                    time: 2000 //2秒关闭（如果不配置，默认是3秒）
                  });
                }
              },'json');
            })
          },
          btn2:function(index,layero){
            fromClear();
            tree.reload('demoId', {
              //新的参数
            });
          }
        });
      }
      if(layEvent==='power'){

      }
    });
  })
  function fromClear(){
    $("#roleName").val("");
  }
</script>
</body>
</html>
